"""
数据比较服务
提供不同数据源之间的数据比较功能
"""

from typing import Dict, Any, TypeVar, Generic
from dataclasses import dataclass
from abc import ABC, abstractmethod


T = TypeVar('T')


@dataclass
class ComparisonResult(Generic[T]):
    """
    比较结果
    
    Attributes:
        source_a: 数据源A的数据
        source_b: 数据源B的数据
        match_rate: 匹配率
        differences: 差异详情
    """
    source_a: T
    source_b: T
    match_rate: float
    differences: Dict[str, Any]


class DataComparator(ABC):
    """数据比较器基类"""
    
    @abstractmethod
    def compare(self, data_a: Any, data_b: Any) -> ComparisonResult:
        """
        比较两个数据源的数据
        
        Args:
            data_a: 数据源A的数据
            data_b: 数据源B的数据
            
        Returns:
            ComparisonResult: 比较结果
        """
        pass


class NumericComparator(DataComparator):
    """数值比较器"""
    
    def compare(self, data_a: float, data_b: float) -> ComparisonResult[float]:
        """
        比较两个数值
        
        Args:
            data_a: 数值A
            data_b: 数值B
            
        Returns:
            ComparisonResult: 比较结果
        """
        # 计算匹配率
        total = max(abs(data_a), abs(data_b))
        match_rate = min(abs(data_a), abs(data_b)) / total if total > 0 else 1.0
        
        # 计算差异
        difference = abs(data_a - data_b)
        difference_percent = (difference / total * 100) if total > 0 else 0
        
        return ComparisonResult(
            source_a=data_a,
            source_b=data_b,
            match_rate=match_rate,
            differences={
                'absolute': difference,
                'percentage': difference_percent
            }
        )


class DictionaryComparator(DataComparator):
    """字典比较器"""
    
    def compare(self, data_a: Dict, data_b: Dict) -> ComparisonResult[Dict]:
        """
        比较两个字典
        
        Args:
            data_a: 字典A
            data_b: 字典B
            
        Returns:
            ComparisonResult: 比较结果
        """
        # 获取所有键
        all_keys = set(data_a.keys()) | set(data_b.keys())
        matched_keys = set(data_a.keys()) & set(data_b.keys())
        
        # 计算匹配率
        match_rate = len(matched_keys) / len(all_keys) if all_keys else 1.0
        
        # 计算差异
        differences = {
            'missing_in_a': list(set(data_b.keys()) - set(data_a.keys())),
            'missing_in_b': list(set(data_a.keys()) - set(data_b.keys())),
            'value_differences': {}
        }
        
        # 比较共同键的值
        for key in matched_keys:
            if data_a[key] != data_b[key]:
                differences['value_differences'][key] = {
                    'source_a': data_a[key],
                    'source_b': data_b[key]
                }
        
        return ComparisonResult(
            source_a=data_a,
            source_b=data_b,
            match_rate=match_rate,
            differences=differences
        )


# 创建全局比较器实例
numeric_comparator = NumericComparator()
dictionary_comparator = DictionaryComparator()
